package org.saasplay.resource;

import com.alibaba.fastjson.JSONObject;

/**
 * 服务资源数据实体注解
 * <p>
 * 1. 使用此注解的实体将成为最基础的服务资源数据实体
 * 2. 将被用着资源过滤 and 资源封装等处理流程当中
 *
 * <p>
 * Service resource data entity annotation
 * <p>
 * 1. Entities that use this annotation become the most basic
 * service resource data entities
 * </p>
 * 2. Will be used in the process of resource filtering and
 * resource encapsulation
 *
 * @author cuishifeng
 */
public class ResourceData {

    private JSONObject resourceJsonObject = new JSONObject();

    public ResourceData(Object resource) {
        if (resource == null) {
            throw new RuntimeException("resource must is not null!");
        }
        this.resourceJsonObject = (JSONObject) JSONObject.toJSON(resource);
    }

    public void addResource(String filed, Object value) throws Exception {
        checkResource();
        this.resourceJsonObject.put(filed, value);
    }

    public void addResource(Object entity) throws Exception {
        checkResource();
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(entity);
        addAll(jsonObject);
    }


    public void addAll(JSONObject jsonObject) throws Exception {
        checkResource();
        this.resourceJsonObject.putAll(jsonObject);
    }

    public void removeResource(String filed) throws Exception {
        checkResource();
        this.resourceJsonObject.remove(filed);
    }


    public void clear() throws Exception {
        checkResource();
        this.resourceJsonObject.clear();
    }

    public Object getResource(String filed) throws Exception {
        return this.resourceJsonObject.get(filed);
    }

    public JSONObject getAllResource() throws Exception {
        return this.resourceJsonObject;
    }

    public <T> T getAllResource(Class<T> clazz) throws Exception {
        return JSONObject.parseObject(this.resourceJsonObject.toJSONString(), clazz);
    }

    private void checkResource() {
        if (this.resourceJsonObject == null) {
            throw new RuntimeException("resource must is not null!");
        }
    }

}
